# stp-import.py
#----------------------------------------------------------------------
# 
"""
    Simple Tagging Import - to import Simple Tagging tags to Wordpress 2.3

    @copyright: 2007 -  Lee Chee Meng skyleecm@gmail.com
    @License: GPL
"""

import MySQLdb

_TAG = "post_tag"

sel_tagpost = "select tag_name, post_id from %s_stp_tags order by tag_name"

sel_term = "select term_id from %s_terms where slug=%s"
sel_taxoterm = "select term_taxonomy_id from %s_term_taxonomy where term_id=%s and taxonomy=%s"
ins_term = "insert into %s_terms (name, slug) values (%s, %s)"
ins_taxoterm = "insert into %s_term_taxonomy (term_id, taxonomy, description, count) values (%s, %s, %s, %s)"
ins_post_taxoterm = "insert into %s_term_relationships (object_id, term_taxonomy_id) values (%s, %s)"
#
sel_term_t = sel_taxoterm_t = ins_term_t = ins_taxoterm_t = ins_post_taxoterm_t = ''

def get_tagposts(cursor, tbl_pref):
    r = cursor.execute(sel_tagpost % tbl_pref)
    rows = cursor.fetchall()
    tags = []
    if not rows: return tags
    curr_tag, postid = rows[0]
    postids = []
    for tag, postid in rows:
        if tag != curr_tag:
            tags.append({'tag': curr_tag, 'posts': postids})
            curr_tag = tag
            postids = [postid]
        else:
            postids.append(postid)
    tags.append({'tag': curr_tag, 'posts': postids})
    return tags


# assume tag is simple, just need to lower and replace space with -
def term_to_slug(term):
    return term.lower().replace(' ', '-')

# slug is unique in terms
def get_termid(slug, cursor):
    r = cursor.execute(sel_term_t, slug)
    row = cursor.fetchone()
    if row:
        return row[0]

# (term_id, taxonomy) is unique in term_taxonomy
def get_taxotermid(termid, cursor):
    r = cursor.execute(sel_taxoterm_t, (termid, _TAG))
    row = cursor.fetchone()
    if row:
        return row[0]
    
def add_term(term, cursor):
    slug = term_to_slug(term)
    try:
        cursor.execute(ins_term_t, (term, slug))
    except Exception, e:
        pass
    return get_termid(slug, cursor)

def add_taxoterm(term, count, cursor):
    termid = add_term(term, cursor)
    try:
        cursor.execute(ins_taxoterm_t, (termid, _TAG, '', count))
    except Exception, e:
        pass
    return get_taxotermid(termid, cursor)

def add_posts_taxoterm(postids, taxotermid, cursor):
    for id in postids:
        try:
            cursor.execute(ins_post_taxoterm_t, (id, taxotermid))
        except Exception, e:
            print e

def import_tags(conn, tbl_pref):
    prepare_sql(tbl_pref)
    cursor = conn.cursor()
    tagposts = get_tagposts(cursor, tbl_pref)
    for tagpost in tagposts:
        postids = tagpost['posts']
        taxotermid = add_taxoterm(tagpost['tag'], len(postids), cursor)
        add_posts_taxoterm(postids, taxotermid, cursor)
        conn.commit()
    return tagposts

def prepare_sql(tbl_pref):
    g = globals()
    for sql in ['sel_term', 'sel_taxoterm', 'ins_term', 'ins_taxoterm', 'ins_post_taxoterm']:
        g[sql+'_t'] = g[sql].replace('%s_', tbl_pref + '_')
    
#----------------------------------------------------------------------
def getConn(tbl_pref):
    prepare_sql(tbl_pref)
    return get_dbuser_conn()

def test_get_tagposts(tbl_pref):
    cursor = getConn(tbl_pref).cursor()
    tagposts = get_tagposts(cursor, tbl_pref)
    for tp in tagposts:
        print tp

def test_get_termid(slug, tbl_pref):
    cursor = getConn(tbl_pref).cursor()
    print get_termid(slug, cursor)

def test_add_term(term, tbl_pref):
    conn = getConn(tbl_pref)
    print add_term(term, conn.cursor())
    conn.commit()
    conn.close()

def test_add_taxoterm(term, count, tbl_pref):
    conn = getConn(tbl_pref)
    print add_taxoterm(term, count, conn.cursor())
    conn.commit()
    conn.close()
    
#----------------------------------------------------------------------
def get_dbuser_conn():
    from getpass import getpass
    db = user = ''
    while not db:
        db = raw_input("Database: ").strip()
    while not user:
        user = raw_input("Database user: ").strip()
    pw = getpass("%s Password: " % user)
    return MySQLdb.connect(host="localhost", user=user, passwd=pw, db=db, charset='utf8')

def do_import_tags():
    conn = get_dbuser_conn()
    tbl_pref = raw_input("Wordpress table prefix [wp]: ").strip()
    if not tbl_pref: tbl_pref = "wp"
    tagposts = import_tags(conn, tbl_pref)
    print "%d tags imported." % len(tagposts)

if __name__ == '__main__':
    import sys
    a = sys.argv
    tbl_pref = "wp"
    if len(a) == 2:
        tbl_pref = a[1]
        test_get_tagposts(tbl_pref)
    else:
        do_import_tags()

        